package com.lazycat.backend.service.impl.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lazycat.backend.mapper.GoodMapper;
import com.lazycat.backend.mapper.StoreMapper;
import com.lazycat.backend.mapper.UserMapper;
import com.lazycat.backend.pojo.Good;
import com.lazycat.backend.pojo.Store;
import com.lazycat.backend.pojo.User;
import com.lazycat.backend.service.store.FetchStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

@Service
public class FetchStoreServiceImpl implements FetchStoreService {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public HashMap<String, Object> fetch(String userId) {
        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();
        storeQueryWrapper.eq("user_id", userId);
        Store store = storeMapper.selectOne(storeQueryWrapper);
        HashMap<String, Object> resp = new HashMap<>();
        if (store == null) {
            resp.put("error_message", "no store");
        } else{
            Integer storeId = store.getId();
            ArrayList<JSONObject> items = new ArrayList<>();
            QueryWrapper<Good> goodQueryWrapper = new QueryWrapper<>();
            goodQueryWrapper.eq("store_id", storeId);
            List<Good> goods = goodMapper.selectList(goodQueryWrapper);
            for (Good good : goods) {
                if (good.getBuyerId() == -2) {
                    continue;
                }
                JSONObject item = new JSONObject();
                item.put("img", Base64.getEncoder().encodeToString(good.getGoodImg()));
                item.put("name", good.getGoodName());
                item.put("price", good.getGoodPrice());
                item.put("id", good.getId());
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("id", userId);
                User user = userMapper.selectOne(userQueryWrapper);
                item.put("buyer", user.getUsername());
                item.put("buyer_id", good.getBuyerId());
                items.add(item);
            }
            resp.put("items", items);
            resp.put("favor", store.getFavor());
            resp.put("store_id", store.getId());
            resp.put("store_name", store.getStoreName());
            resp.put("error_message", "success");
        }
        
        return resp;
    }
}
